<?php

namespace App\ApiBackend;

use App\Http\Controllers\ApiBaseController;
use Illuminate\Support\Facades\DB;

/**
 *  上传
 */
class Upload extends ApiBaseController
{
  private array $fileAllowType = [
    'pdf',
  ];
  private int $fileAllowSize = 5;// 单位M

  /**
   * 参数检查
   */
  protected function check(): void
  {

    try {
      request()->validate([
        'file' => 'required',
      ]);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = $exception->getMessage();
    }

  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $file = request()->file('file');
    $module = request('module','file');
    //检测
    if (!in_array($file->extension(), $this->fileAllowType)) {//类型限制
      $this->result['code'] = 1;
      $this->result['message'] = "文件 " . $file->extension() . " 格式不支持";
      return;
    }
    if ($file->getSize() > $this->fileAllowSize* 1024 * 1024) {//大小限制
      $this->result['code'] = 1;
      $this->result['message'] = "文件 " . (int)($file->getSize() / 1024 / 1024) . "M 超出{$this->fileAllowSize}M限制";
      return;
    }
    // 主逻辑
    try {
      $path = $file->store('public/file/' . date('Ymd') );
    } catch (\Exception $exception) {
      $this->result['code'] = 1;
      $this->result['message'] = $exception->getMessage();
      return;
    }
    //插入图片表
    DB::table('file')->insert([
      'type'=>$file->extension(),
      'module'=>$module,
      'path'=>str_replace('public/', '/storage/', $path),
      'name'=>$file->getClientOriginalName(),
      'size'=>$file->getSize(),
      'createTime'=>date('Y-m-d H:i:s'),
    ]);

    $domain = config('app.url');
    $this->result['url'] = $domain  . str_replace('public/', '/storage/', $path);

    return;
  }
}
